package network.httpserver;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * 简单Http服务器
 * @author glogo
 *
 */
public class HttpServer {

	private Selector selector;
	private ServerSocketChannel serverSocket;
	private int port = 8080;
	
	public HttpServer() throws IOException{
		selector = Selector.open();
		serverSocket = ServerSocketChannel.open();
		serverSocket.socket().setReuseAddress(true);
		serverSocket.configureBlocking(false);
		serverSocket.bind(new InetSocketAddress(port));
	}
	
	public void service() throws IOException{
		serverSocket.register(selector, SelectionKey.OP_ACCEPT, new AcceptHandler());
		for(;;){
			int n = selector.select();
			if(n == 0)	continue;
			Set<SelectionKey> readyKeys = selector.selectedKeys();
			Iterator<SelectionKey> it = readyKeys.iterator();
			while(it.hasNext()){
				SelectionKey key = null;
				try{
					key = it.next();
					it.remove();
					final Handler handler = (Handler) key.attachment();
					handler.handle(key);
				}catch(IOException ioe){
					try{
						if(key != null){
							key.cancel();
							key.channel().close();
						}
					}catch(IOException io){io.printStackTrace();}
				}
			}
		}
	}
	
	public static void main(String[] args) throws IOException{
		new HttpServer().service();
	}
}
